package com.turtle3d;

import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.media.j3d.Shape3D;

import com.turtle3d.formallanguage.grammar.Grammar;
import com.turtle3d.visualizator.Visualizator;

public abstract class ResourceManager
{

	public static final String grammarsPackage = "com.turtle3d.user.grammars";
	public static final String visualizatorsPackage = "com.turtle3d.user.visualizators";

	private static File[] listClassFiles(String packageName)
	{
		try
		{
			String pckgname = packageName;
			URL packageURL = Thread.currentThread().getContextClassLoader()
					.getResource(pckgname.replace('.', '/'));
			File directory = new File(URLDecoder.decode(packageURL.getFile(),
					"utf8"));

			return directory.listFiles(new ClassFileFilter());
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(-1);
			return null;
		}
	}

	public static ArrayList<Grammar> getGrammars()
	{
		ArrayList<Grammar> grammars = new ArrayList<Grammar>();

		for (File f : listClassFiles(grammarsPackage))
		{
			String className = getClassSimpleName(f);
			try
			{
				Grammar g = (Grammar) Thread.currentThread().getClass()
						.forName(grammarsPackage + "." + className)
						.newInstance();
				grammars.add(g);
			}
			catch (Exception e)
			{
				// ignore it
			}

		}

		return grammars;
	}
	
	public static ArrayList<Visualizator> getVisualizators(){
		ArrayList<Visualizator> visualizators = new ArrayList<Visualizator>();

		for (File f : listClassFiles(visualizatorsPackage))
		{
			String className = getClassSimpleName(f);
			try
			{
				Visualizator g = (Visualizator) Thread.currentThread().getClass()
						.forName(visualizatorsPackage + "." + className)
						.newInstance();
				visualizators.add(g);
			}
			catch (Exception e)
			{
				// ignore it
			}

		}

		return visualizators;
	}
	
	public static Shape3D getShape3D(String path){
		return Shape3DCacheLoader.getShape3DCacheLoader().createShape3D(path);
	}

	private static String getClassSimpleName(File file)
	{
		return file.getName().substring(0, file.getName().lastIndexOf('.'));
	}

}

final class ClassFileFilter implements FileFilter
{

	public boolean accept(File pathname)
	{
		String name = pathname.getName();
		String ext = name.substring(name.lastIndexOf('.') + 1, name.length());
		return ext.equals("class");
	}
}
